//
//  SearchViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/8/1.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD

private let searchItemCellIdentifier = "SearchItemCell"

struct SearchResultItem {
  enum AlbumType: String {
    case vip = "vip"
    case normal = "normal"
  }
  
  var id: Int
  var albumName: String
  var type: AlbumType
  var coverImageURL: URL
}

class SearchViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var searchBar: UISearchBar!
  @IBOutlet private weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var resultItems: [SearchResultItem]?
  private var selectedAlbumIdentifier = -1
  private var keyword: String?
  
  // MARK: - Private methods

  
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    searchBar.becomeFirstResponder()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if selectedAlbumIdentifier >= 0 && segue.identifier == "ShowAlbumDetailFromSearch" {
      let albumDetailViewController = segue.destination as! AlbumDetailViewController
      albumDetailViewController.albumIdentifier = selectedAlbumIdentifier
    }
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

extension SearchViewController: UISearchBarDelegate {
  func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
    if let keyword = searchBar.text?.trim() {
      self.keyword = keyword
      API.shared.requestAPI (
        APIURLStrings.search(keyword: keyword),
        method: .get,
        header: API.shared.memeberHeader,
        successCallback: { json in
          self.resultItems = nil
          
          if let resultArray = json["albums"].array, resultArray.count > 0 {
            self.resultItems = resultArray.map {
              SearchResultItem (
                id: $0["id"].intValue,
                albumName: $0["album_name"].stringValue,
                type: SearchResultItem.AlbumType(rawValue: $0["type"].stringValue)!,
                coverImageURL: URL(string: "\(APIURLStrings.imagePrefix)/\($0["cover"])")!
              )
            }
            HUD.hide()
            self.searchBar.resignFirstResponder()
          } else {
            HUD.flash(.label("没有找到节目"), delay: 1.5)
          }
          
          self.tableView.reloadData()
      }) { (_, _) in
        HUD.flash(.labeledError(title: "搜索失败", subtitle: "请重试"), delay: 1.5)
      }
    }
  }
  
  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.count == 0 {
      resultItems = nil
      tableView.reloadData()
    }
  }
}

extension SearchViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = resultItems?.count, count > 0 {
      return count
    } else {
      return 0
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: searchItemCellIdentifier, for: indexPath) as! SearchItemCell
    let resultItem = resultItems![indexPath.row]
    let isVipAlbum = (resultItem.type == .vip)
    cell.prepare (
      coverImageURL: resultItem.coverImageURL,
      contentName: resultItem.albumName,
      isVipAlbum: isVipAlbum,
      keyword: keyword
    )
    return cell
  }
}

extension SearchViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let resultItem = resultItems![indexPath.row]
    selectedAlbumIdentifier = resultItem.id
    performSegue(withIdentifier: "ShowAlbumDetailFromSearch", sender: self)
    tableView.deselectRow(at: indexPath, animated: true)
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if resultItems != nil {
      return SearchItemCell.defaultHeight
    } else {
      return NoDataTableCell.defaultHeight
    }
  }
}
